package com.jluzh10.learning.service.Impl;

import com.jluzh10.learning.dao.ChapterMapper;
import com.jluzh10.learning.dao.UsersStudyMapper;
import com.jluzh10.learning.domain.Chapter;
import com.jluzh10.learning.domain.ChapterExample;
import com.jluzh10.learning.domain.UsersStudy;
import com.jluzh10.learning.domain.UsersStudyExample;
import com.jluzh10.learning.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author yzg
 * @create 2019/5/27
 */
@Service
@Transactional
public class ChapterServiceImpl implements ChapterService {
    private final ChapterMapper chapterMapper;
    private final UsersStudyMapper studyMapper;

    @Autowired
    public ChapterServiceImpl(ChapterMapper chapterMapper, UsersStudyMapper studyMapper) {
        this.chapterMapper = chapterMapper;
        this.studyMapper = studyMapper;
    }

    @Override
    public List<Chapter> list(Integer courseId) {
        ChapterExample chapterExample=new ChapterExample();
        chapterExample.setOrderByClause("sort");
        chapterExample.createCriteria().andStateEqualTo((byte) 1).andCourseIdEqualTo(courseId);
        return chapterMapper.selectByExample(chapterExample);
    }

    @Override
    public Chapter findById(int chapterId,int userId) {
        //获取章节信息
        Chapter chapter = chapterMapper.selectByPrimaryKey(chapterId);
        //查询用户是否第一次学习该章节
        UsersStudyExample example=new UsersStudyExample();
        example.createCriteria().andChapterIdEqualTo(chapterId).andUserIdEqualTo(userId);
        List<UsersStudy> studies = studyMapper.selectByExample(example);
        if (studies.size()>0){
            //学习过该章节，更新最后学习时间
            studyMapper.updateByPrimaryKeySelective(new UsersStudy(studies.get(0).getId(),new Date()));
        }else {
            //用户第一次学习该章节
            UsersStudy study = new UsersStudy();
            study.setCreateTime(new Date());
            study.setLastTime(new Date());
            study.setChapterId(chapterId);
            study.setCourseId(chapter.getCourseId());
            study.setState((byte) 0);
            study.setUserId(userId);
            studyMapper.insertSelective(study);
        }
        return chapter;
    }
}
